import axios from "axios";
// 引入 axios 实例
import type {AxiosInstance} from "axios";
import {ElLoading} from "element-plus";
// 引入 Loading实例
import { LoadingInstance } from 'element-plus/lib/components/loading/src/loading.d.js';

const DEAFULT_LOADING = false;
type RequestConfig = {
  url?: string;
  method?: "get" | "post" | "delete" | "patch";
  params?: any;
  data?: any;
  showLoading?: boolean;
};

class Request {
  instance: AxiosInstance; //axios实例
  showLoading: boolean; // 是否开启Loading
  loading?: LoadingInstance; //Loading实例
  constructor(config: RequestConfig) {
    this.instance = axios.create(config);
    this.showLoading = config.showLoading ?? DEAFULT_LOADING;
    //添加拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: "正在请求数据...",
            background: "regba(0,0,0,0.5)"
          });
        }
        return config;
      },
      (err) => {
        return err;
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        //将loading移除
        this.loading?.close();
        const data = res.data as any;
        return data;
      },
      (err) => {
        if (err.response.status === 404) {
          console.log("页面不见了！");
        }
        return err;
      }
    );
  }
	request<T>(config: RequestConfig): Promise<T> {
		return new Promise((resolve, reject) => {
			if (config.showLoading === true) {
				this.showLoading = config.showLoading;
			}
			this.instance
				.request<any, any>(config)
				.then((res: any) => {
					this.showLoading = DEAFULT_LOADING;
					resolve(res);
				})
				.catch(err => {
					this.showLoading = DEAFULT_LOADING;
					reject(err);
					return err;
				});
		});
}
 
  get<T>(config: RequestConfig): Promise<T> {
    return this.request<T>({...config, method: "get"});
  }
 
  post<T>(config: RequestConfig): Promise<T> {
    return this.request<T>({...config, method: "post"});
  }
 
  delete<T>(config: RequestConfig): Promise<T> {
    return this.request<T>({...config, method: "delete"});
  }
 
  patch<T>(config: RequestConfig): Promise<T> {
    return this.request<T>({...config, method: "patch"});
  }
}
 
export default Request;